<template>
    <Cell :class="$style.cell" :border="border" arrow @tap="show = true">
        <text><slot></slot></text>
        <template #right>
            <template v-if="columns.length > 0">
                <template v-if="model?.length > 0">{{ showStr(model) }}</template>
            </template>
        </template>
    </Cell>

    <nut-popup v-model:visible="show" position="bottom">
        <nut-picker v-model="val" :field-names="{ text: 'name', value: 'value', children: 'children' }" :columns="columns" @confirm="confirm" @cancel="show = false" />
    </nut-popup>
</template>

<script lang="ts" setup>
    import Cell from '@/components/Cell.vue'
    import { ref, watch } from 'vue';
    const show = ref(false);

    interface Option {
        name : string;
        value : any
    }

    const props = defineProps<{
        columns : Option[] | Option[][],
        border? : boolean;
        default? : (string|number)[]
    }>()

    
    const model = defineModel<(string|number)[]>()
    const val = ref()

    if(model.value && model.value.length > 0) {
        val.value = [...model.value]
    }else {
        if(props.default && props.default.length > 0) {
            val.value = [...props.default]
        }
    }

    watch(model, (newv, oldv) => {
        val.value = [...newv]
    })

    

    const emit = defineEmits<{
        (e : 'confirm', value : any)
    }>()


    function showStr(values:(string|number)[]) {
        if(values.length == 1) {
            const column = props.columns.find(item => item.value == values[0])
            return column.name
        }else {
            let str = ''
            values.forEach((v, i) => {
                const column = props.columns[i].find(item => item.value == values[i])
                str += column.name
            })
            return str
        }   
    }

    const confirm = (e) => {
        model.value = [...e.selectedValue]
        show.value = false;

        emit('confirm', e.selectedValue)
    };
</script>

<style lang="scss" module>
    .cell{
            height: 88px;
            background: #fff;
            border-radius: 10px;
            padding: 0 $space;
            border-bottom: 1px solid $page-background-color;
        }
</style>